package cn.dicraft.netty.client;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;

import java.net.InetSocketAddress;

/**
 * 消费端
 * @author 烛远
 * @date 2024/8/29 17:20
 */
public class HelloClient {
    public static void main(String[] args) throws InterruptedException {
        //1. 创建启动器
        new Bootstrap()
                //2. 添加eventLoop
                .group(new NioEventLoopGroup())
                //3. 选择客户端的channel实现
                .channel(NioSocketChannel.class)
                //4. 添加处理器
                .handler(new ChannelInitializer<NioSocketChannel>() {
                    @Override //在建立连接后被调用
                    protected void initChannel(NioSocketChannel nioSocketChannel) throws Exception {
                        // 把字符串转化成bytebuffer, 发送给NioEventLoopGroup
                        nioSocketChannel.pipeline().addLast(new StringEncoder());
                    }
                })
                //5. 连接到服务器
                .connect(new InetSocketAddress("localhost",8080))
                .sync()  // 阻塞方法，直到连接建立
                .channel() // 代表连接对象
                //6. 向服务器发送数据
                .writeAndFlush("hello,world");
    }
}
